package cn.tedu.person.filter;

import cn.tedu.person.security.LoginPrincipal;
import cn.tedu.person.web.JsonResult;
import cn.tedu.person.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    public static final int JWT_MIN_LENGTH=113;

    @Override
    protected void doFilterInternal(
            HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse,
            FilterChain filterChain) throws ServletException, IOException {

        // 清空SecurityContext，避免【此前携带JWT成功访问后，在接下来的一段时间内不携带JWT也能访问】
//        SecurityContextHolder.clearContext();

        //根据业内的惯用的做法，客户端应该将jwt保存在请求头中名为Authorization
        String jwt=httpServletRequest.getHeader("Authorization");
        log.debug("尝试接收客户端携带的jwt数据 jwt:{}",jwt);

        //判断客户端是否携带了基本有效的jwt
        if(!StringUtils.hasText(jwt) || jwt.length()<JWT_MIN_LENGTH){
            //客户端没有携带有效的jwt 则放行 交给后端来处理
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            //终止当前的方法 因为后续的代码是对携带了jwt的进行处理
            return;
        }

        // 客户端携带了基本有效的JWT，则尝试解析JWT
        String secretKey = "kU4jrFA3iuI5jn25u743kfDs7a8pFEwS54hm";
        Claims claims= null;
        httpServletResponse.setContentType("application/json; charset=utf-8");
        try {
            claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (ExpiredJwtException e) {
            String message="您的登录信息已过期，请重新登录！";
            log.warn(message);
            JsonResult jsonResult=JsonResult.fail(ServiceCode.ERR_JWT_SIGNATURE,message);
            String jsonResultString=JSON.toJSONString(jsonResult);
            PrintWriter writer=httpServletResponse.getWriter();
            writer.println(jsonResultString);
            writer.close();
            return;
        } catch (UnsupportedJwtException e) {
            e.printStackTrace();
        } catch (MalformedJwtException e) {
            String message = "非法访问！";
            log.warn(message);
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_MALFORMED, message);
            String jsonResultString = JSON.toJSONString(jsonResult);
            PrintWriter writer = httpServletResponse.getWriter();
            writer.println(jsonResultString);
            writer.close();
            return;
        } catch (SignatureException e) {
            String message = "非法访问！";
            log.warn(message);
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_SIGNATURE, message);
            String jsonResultString = JSON.toJSONString(jsonResult);
            PrintWriter writer = httpServletResponse.getWriter();
            writer.println(jsonResultString);
            writer.close();
            return;
        } catch (Throwable e) {
            String message = "服务器忙，请稍后再次尝试！（开发过程中，如果看到此提示，请检查控制台的信息，并在JWT过滤器补充处理此异常）";
            log.warn(message);
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_UNKNOWN, message);
            String jsonResultString = JSON.toJSONString(jsonResult);
            PrintWriter writer = httpServletResponse.getWriter();
            writer.println(jsonResultString);
            writer.close();
        }

        Long id=claims.get("id",Long.class);
        String username=claims.get("name",String.class);
        String authoritiesJsonString=claims.get("authoritiesJsonString",String.class);
        log.debug("从JWT中解析得到的管理员ID：{}", id);
        log.debug("从JWT中解析得到的管理员用户名：{}", username);
        log.debug("从JWT中解析得到的管理员权限列表：{}", authoritiesJsonString);

        // 基于解析JWT的结果创建当事人Authentication对象
        LoginPrincipal loginPrincipal=new LoginPrincipal();
        loginPrincipal.setId(id);
        loginPrincipal.setUsername(username);

        Object principal=loginPrincipal;
        Object credentials=null;
        List<SimpleGrantedAuthority> authorities=
                JSON.parseArray(authoritiesJsonString,SimpleGrantedAuthority.class);
//        authorities.add(new SimpleGrantedAuthority("山寨权限"));
        Authentication authentication=new UsernamePasswordAuthenticationToken(
                principal,credentials,authorities
        );

        // 将Authentication存入到SecurityContext中
        log.debug("向SecurityContext中存入Authentication：{}", authentication);
        SecurityContext securityContext= SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);

        //过滤器继续执行 相当于放行
        filterChain.doFilter(httpServletRequest,httpServletResponse);

    }

}
